package com.fundcrawler.h2;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.h2.server.web.WebServlet;
import org.h2.tools.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.io.File;
import java.sql.SQLException;

/**
 * @author litianlin
 * @date 2023/11/23 10:18
 * @description: h2示例
 */
@Slf4j
public class H2ServerDemo {
    /**数据库文件不放在resources文件夹下，避免compile时异常*/
    public static final String H2_BASE_DIR = ArgConstant.PROJECT_PATH+ "/db/h2/";

    public static void main(String[] args) throws Exception{
        File file = new File(H2_BASE_DIR);
        if(!file.exists()){
            file.mkdirs();
        }
        H2ServerDemo demo = new H2ServerDemo();
        demo.startWebServer();
        demo.startTcpServer();
    }

    /**
     * 只是浏览器控制台，无数据库服务
     * 不支持连接不存在的数据库
     */
    public void startWebServer() throws Exception{
        Server server;
        try {
            server = Server.createWebServer(
                    "-web",
                    "-webAllowOthers",
                    "-webPort", "8083",
                    // 使用守护线程
					"-webDaemon",
                    // 控制台密码；admin。后一个作用？
                    "-webAdminPassword", "admin", "111111"
            ).start();
            log.info(server.getURL());
        } catch (SQLException e) {
            log.error("", e);
        }
    }

    /**
     * 数据库服务
     * jdbc:h2:tcp://localhost:9092/./h2
     *  默认端口：9092
     *  默认数据库：h2
     *  必须走tcp连接，才能创建数据库
     */
    public void startTcpServer() throws Exception {
        Server server = Server.createTcpServer(
                "-tcp",
                "-tcpAllowOthers",
                "-tcpPort", "9092",
                // 使用守护线程
                "-tcpDaemon",
                "-ifNotExists",
                "-baseDir", H2_BASE_DIR
        ).start();
        Thread.currentThread().join();// 阻塞线程；测试完成时会关闭h2
//		server.stop();
    }

    @Bean//启动webServer
    public ServletRegistrationBean<WebServlet> registH2WebServlet() {
        ServletRegistrationBean<WebServlet> srb = new ServletRegistrationBean<>(new WebServlet());
        srb.setInitParameters(MapUtil.builder("-webAllowOthers", "")
                .put("-trace", "")
                .put("-browser", "")
                .build());
        srb.addUrlMappings("/h2console/*");
        return srb;
    }

    @Bean(name="tcpServer",initMethod="start",destroyMethod="stop")
    @ConditionalOnExpression("${h2.enableAppServer:true}==true")
    @Value("${h2.serverConfig:}")
    public Server tcpServer(String[] configs) throws SQLException {
        Server server = Server.createTcpServer(configs);
        log.info(server.getURL());
        return server;
    }
}

